<template>
  <a-modal
    :width="'100%'"
    :style="{ top: 0, paddingBottom: 0 }"
    :bodyStyle="{
      backgroundColor: '#F0F2F5',
      padding: '8px',
      height: 'calc(100vh - 55px)',
      overflow: 'auto'
    }"
    :visible="visible"
    title="设备分区"
    :footer="null"
    @update:visible="updateVisible"
  >
    <div class="ele-body">
      <a-card :bordered="false">
        <div class="group-container">
          <!-- 左侧设备列表 -->
          <div class="device-list">
            <div class="section-title">未分区设备</div>
            <div
              class="devices-container"
              @dragover.prevent
              @drop="onDropToUnassigned"
            >
              <div
                v-for="device in unassignedDevices"
                :key="device.recordId"
                class="device-item"
                draggable="true"
                @dragstart="onDragStart(device, 'unassigned')"
              >
                <div class="device-info">
                  <div class="device-row">
                    <span>设备ID: {{ device.recordId }}</span>
                    <span class="mac-info">MAC: {{ device.macId }}</span>
                    <span class="mac-info">编号: {{ device.lable1 }}</span>
                    <span class="mac-info">区域: {{ device.areaName }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧分组列表 -->
          <div class="group-list">
            <div class="section-title">
              设备分区
              <a-button 
                type="link" 
                size="small" 
                @click="toggleAllGroups"
                style="float: right"
              >
                {{ allGroupsExpanded ? '全部收起' : '全部展开' }}
              </a-button>
            </div>
            <div class="groups-container">
              <div
                v-for="group in groups"
                :key="group.groupId"
                class="group-item"
              >
                <div class="group-header" @click="toggleGroup(group)">
                  <span class="group-title">
                    <down-outlined v-if="group.expanded" />
                    <right-outlined v-else />
                    组名:{{ group.groupName }}
                    <span class="device-count">({{ group.devices?.length || 0 }})</span>
                  </span>
                </div>
                <div
                  v-show="group.expanded"
                  class="group-devices"
                  :class="{ 'drag-over': isDragOver === group.groupId }"
                  @dragover.prevent
                  @dragenter="handleDragEnter(group.groupId)"
                  @dragleave="handleDragLeave(group.groupId)"
                  @drop="onDropToGroup(group)"
                >
                <div
                  v-for="device in group.devices"
                  :key="device.recordId"
                  class="device-item"
                  :class="{ 'dragging': draggingDevice?.recordId === device.recordId }"
                  draggable="true"
                  @dragstart="onDragStart(device, group.groupId)"
                  @dragend="onDragEnd"
                >
                    <div class="device-info">
                      <div class="device-row">
                        <span>设备ID: {{ device.recordId }}</span>
                        <span class="mac-info">MAC: {{ device.macId }}</span>
                        <span class="mac-info">编号: {{ device.lable1 }}</span>
                        <span class="mac-info">区域: {{ device.areaName }}</span>
                      </div>
                    </div>
                    <a-button
                      type="link"
                      size="small"
                      @click="removeFromGroup(device, group)"
                    >
                      移除
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作按钮 -->
        <div class="footer-actions">
          <a-button type="primary" @click="saveAssignments" :loading="saving">
            保存分配
          </a-button>
        </div>
      </a-card>
    </div>
  </a-modal>
</template>

<script>
import { DeviceSprayCameraApi } from '@/api/property/spraycamera/DeviceSprayCameraApi'
import { DeviceSprayCameraGroupApi } from '@/api/property/spraycamera/DeviceSprayCameraGroupApi'
import { DeviceSprayCameraGroupRecordApi } from '@/api/property/spraycamera/DeviceSprayCameraGroupRecordApi'
import { message } from 'ant-design-vue'
import { DownOutlined, RightOutlined } from '@ant-design/icons-vue'


export default {
  name: 'DeviceManagerdeviceCameraGroupAssignment',
  components: {
    DownOutlined,
    RightOutlined
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 菜单数据
    data: Object
  },
  created() {
  },
  data() {
    return {
      unassignedDevices: [],
      groups: [],
      draggingDevice: null,
      draggingSource: null,
      saving: false,
      isDragOver: null, // 添加拖拽状态标识
      allGroupsExpanded: true, // 添加控制所有分组展开状态的变量
    }
  },
  async mounted() {
    await this.loadData()
  },
  methods: {
    // 添加拖拽相关方法
    handleDragEnter(groupId) {
      this.isDragOver = groupId;
    },

    handleDragLeave(groupId) {
      if (this.isDragOver === groupId) {
        this.isDragOver = null;
      }
    },
    onDragEnd() {
      this.isDragOver = null;
      this.draggingDevice = null;
      this.draggingSource = null;
    },
    toggleGroup(group) {
      if (!group.hasOwnProperty('expanded')) {
        this.$set(group, 'expanded', true);
      }
      group.expanded = !group.expanded;
    },
    // 切换所有分组的展开状态
    toggleAllGroups() {
      const newState = !this.allGroupsExpanded;
      this.groups.forEach(group => {
        group.expanded = newState;
      });
      this.allGroupsExpanded = newState;
    },
    
    async loadData() {
      try {
        // 加载该牛舍下的所有设备
        const devicesResult = await DeviceSprayCameraApi.list({ queryOxtallId: this.data.oxtallId })
        // 加载所有分组
        const groupsResult = await DeviceSprayCameraGroupApi.list({ oxtallId: this.data.oxtallId })

        this.groups = (groupsResult || []).map(group => ({
          ...group,
          expanded: true // 默认展开所有分组
        }));

        // 初始化未分组设备列表
        const assignedDeviceIds = this.groups.reduce((acc, group) => {
          return acc.concat(group.devices?.map(d => d.recordId) || [])
        }, [])

        this.unassignedDevices = (devicesResult || []).filter(
          device => !assignedDeviceIds.includes(device.recordId)
        )
      } catch (error) {
        message.error('加载数据失败')
      }
    },

    onDragStart(device, source) {
      this.draggingDevice = device
      this.draggingSource = source
    },

    onDropToUnassigned() {
      if (!this.draggingDevice) return

      if (this.draggingSource === 'unassigned') return

      // 从原分组中移除
      const sourceGroup = this.groups.find(g => g.groupId === this.draggingSource)
      if (sourceGroup) {
        sourceGroup.devices = sourceGroup.devices.filter(
          d => d.recordId !== this.draggingDevice.recordId
        )
      }

      // 添加到未分组列表
      this.unassignedDevices.push(this.draggingDevice)

      this.draggingDevice = null
      this.draggingSource = null
    },

    onDropToGroup(targetGroup) {
      if (!this.draggingDevice) return

      if (this.draggingSource === targetGroup.groupId) return

      // 从源位置移除
      if (this.draggingSource === 'unassigned') {
        this.unassignedDevices = this.unassignedDevices.filter(
          d => d.recordId !== this.draggingDevice.recordId
        )
      } else {
        const sourceGroup = this.groups.find(g => g.groupId === this.draggingSource)
        if (sourceGroup) {
          sourceGroup.devices = sourceGroup.devices.filter(
            d => d.recordId !== this.draggingDevice.recordId
          )
        }
      }

      // 添加到目标分组
      if (!targetGroup.devices) {
        targetGroup.devices = []
      }
      targetGroup.devices.push(this.draggingDevice)

      this.draggingDevice = null
      this.draggingSource = null
    },

    removeFromGroup(device, group) {
      group.devices = group.devices.filter(d => d.recordId !== device.recordId)
      this.unassignedDevices.push(device)
    },

    async saveAssignments() {
      try {
        this.saving = true
        const assignments = {}
        this.groups.forEach(group => {
          assignments[group.groupId] = group.devices?.map(d => d.recordId) || []
        })

        let updateParams = {
          "groupRecordIds" : assignments,
          "oxtallId" : this.data.oxtallId
        };
        console.log(assignments);
        let result = DeviceSprayCameraGroupRecordApi.assignment(updateParams);
        result.then(result => {
          // 移除加载框
          this.saving = false;

          // 提示添加成功
          message.success('保存成功');

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.saving = false
        });

      } catch (error) {
        message.error('保存失败')
      } finally {
        this.saving = false
      }
    },
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
  }
}
</script>

<style scoped>
.group-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  height: calc(100vh - 150px); /* 调整容器高度 */
  overflow: hidden;
}

.device-list,
.group-list {
  flex: 1;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  display: flex;
  flex-direction: column; /* 改为纵向布局 */
  height: 100%; /* 继承父容器高度 */
}

.section-title {
  padding: 12px;
  font-weight: bold;
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0; /* 防止标题被压缩 */
}

.devices-container,
.groups-container {
  padding: 12px;
  flex: 1;
  overflow-y: auto;
  height: calc(100% - 20px); /* 调整内容区域高度，减少内边距影响 */
}

.group-item {
  margin-bottom: 16px;
  background: #fff; /* 添加背景色 */
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.group-devices {
  min-height: 100px;
  padding: 8px;
  background-color: #fafafa;
  border-radius: 4px;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

/* 添加拖拽目标样式 */
.group-devices.drag-over {
  background-color: #e6f7ff;
  border: 2px dashed #1890ff;
}

/* 优化设备项样式 */
.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.device-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  border-color: #40a9ff;
}

/* 拖拽时的样式 */
.device-item.dragging {
  opacity: 0.5;
  transform: scale(0.95);
}

.device-info {
  flex: 1;
}

.group-item {
  margin-bottom: 16px;
}

.group-header {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
}

.group-header:hover {
  background-color: #e6f7ff;
}

.device-count {
  color: #999;
  font-size: 12px;
}

.group-devices {
  min-height: 100px;
  padding: 8px;
  background-color: #fafafa;
  border-radius: 4px;
}

.footer-actions {
  text-align: center;
  margin-top: 16px;
  margin-bottom: 16px; /* 添加底部间距 */
  padding: 8px;
  background: #fff;
  position: sticky; /* 使按钮固定在底部 */
  bottom: 0;
  z-index: 1;
}

/* 添加以下样式 */
:deep(.ant-modal) {
  max-width: 100%;
  top: 0;
  padding-bottom: 0;
  margin: 0;
}

:deep(.ant-modal-content) {
  height: 100vh;
  border-radius: 0;
  display: flex;
  flex-direction: column;
}

:deep(.ant-modal-body) {
  height: calc(100vh - 55px); /* 调整模态框body高度 */
  padding: 12px;
  flex: 1;
  overflow: auto;
}

.device-row {
  display: flex;
  gap: 16px;
  align-items: center;
}

.mac-info {
  color: #666;
}
</style>
